<template>
  <div class="article-list">
    <!-- 下拉刷新，必须将van-list包起来 success-duration成功提示展示时长 -->
    <van-pull-refresh
      v-model="isreFreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重试"
        @load="onLoad"
      >
        <article-item
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        >
        </article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article_item'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      error: false, //   控制错误提示
      isreFreshLoading: false, //   控制刷新提示
      timestamp: null, // 请求下一页数据的时间戳
      refreshSuccessText: '刷新成功' // 下拉刷新成功提示文本
    }
  },
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      try {
        //   获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // 将数据添加到list
        const { results } = data.data
        // 数组展开符，会将数据一个一个拿出来
        this.list.push(...results)
        // 设置本次加载中 loading 状态结束
        this.loading = false
        // 判断数据是否加载完
        if (results.length) {
          // 更新获取下一页数据
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没数据就结束
          this.finished = true
        }
      } catch (err) {
        this.loading = false // 关闭 loading 效果
        this.error = true // 开启错误提示
      }
    },
    async onRefresh () {
      try {
        //   获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // 将数据追加到顶部
        const { results } = data.data
        this.list.unshift(...results)
        // 关闭下拉刷新loading
        this.isreFreshLoading = false
        // 更新下拉刷新成功提示文本
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        this.isreFreshLoading = false
        this.refreshSuccessText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
